package com.sanmina.route.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sanmina.route.dao.RouteDao;
import com.sanmina.route.dao.RouteDaoImpl;
import com.sanmina.route.entity.Route;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet("/searchRoute")
public class SearchRouteAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4195725175492885170L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int start = Integer.valueOf(req.getParameter("start"));
		int limit = Integer.valueOf(req.getParameter("limit"));
		int page = Integer.valueOf(req.getParameter("page"));
		String name = "";
		name = req.getParameter("name");
		
		int end = 0;
		List<Route> routes = new ArrayList<Route>();
		
		RouteDao dao = new RouteDaoImpl();
		
		if (name!=null&&name!="") {
			routes=dao.searchRouteByName(name);
		}else{
			routes=dao.listAllRoute();
		}
		
		if(page!=1){
			if(start>routes.size()){
				start= 0;
			}
		}
		
		
		List<Route> subRoutesList = new ArrayList<Route>();
		
		if (limit > 20)
			limit = 20;
		if ((routes.size() - start) < limit || limit == 0) {
			end = routes.size();
		} else {
			end = start + limit;
		}
		
		subRoutesList = routes.subList(start, end);
		JSONArray ja;
		JSONObject jo = new JSONObject();
		ja = JSONArray.fromObject(subRoutesList);
		jo.put("routes", ja);
		jo.put("routeCount", routes.size());
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().print(jo);
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
